# -*- coding: utf-8 -*-

import sys
import time
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
#import cv2
import os
from PyQt5 import QtCore, QtGui, QtWidgets

import xml.etree.ElementTree as ET


import svgutils.transform as sg
from svgutils.compose import Figure


import cairosvg


#svg_path1 = 'C:/Users/16006/Desktop/解析软件的开发/svg文件处理前/30-40-test.svg'
#svg_path2 = 'C:/Users/16006/Desktop/解析软件的开发/svg文件处理前/40-40-东宝5211314-2.svg'
#png_path1 = '1.png'
#png_path2 = '2.png'

#ele_root = ET.parse(svg_path1).getroot()

#width = ele_root.get('width')
#height = ele_root.get('height')
#cairosvg.svg2png(url=svg_path1, write_to=png_path1,dpi=600)
#cairosvg.svg2png(url=svg_path2, write_to=png_path2,dpi=600)
print(121)


#merged_svg = ET.Element('svg')


#svg1 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\60-35-大哪吒和金刚葫芦娃+卡▲-1.svg').getroot()
#svg2 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\60-35-大哪吒和金刚葫芦娃+卡▲-2.svg').getroot()


## Create a new SVG element


## Add the attributes from one of the original SVGs to the merged SVG
#merged_svg.attrib = svg2.attrib

## Add the contents of each SVG to the merged SVG
#for elem in svg1:
#    merged_svg.append(elem)
#for elem in svg2:
#    merged_svg.append(elem)


## Write the merged SVG to a file
#ET.ElementTree(merged_svg).write('merged.svg')



#merged_svg2 = ET.Element('svg')


#svg3 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-1.svg').getroot()
#svg4 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-2.svg').getroot()


## Create a new SVG element


## Add the attributes from one of the original SVGs to the merged SVG
#merged_svg2.attrib = svg3.attrib

## Add the contents of each SVG to the merged SVG
#for elem in svg3:
#    merged_svg.append(elem)
#for elem in svg4:
#    merged_svg.append(elem)


## Write the merged SVG to a file
#ET.ElementTree(merged_svg).write('merged2.svg')










class MergeSvg(object):
    dict_svg = {}
    dir_path = './'
    def split_svg(self, svg_list, path_len, isdir):
        if isdir == 1:
            for ele in svg_list:
                curr_key =  ele[path_len + 1: -6]
                if curr_key in self.dict_svg.keys():
                    self.dict_svg[curr_key].append(ele)
                else:
                    self.dict_svg[curr_key] = []
                    self.dict_svg[curr_key].append(ele)
            #self.merge_svg(self.dict_svg)
            self.merge_svg(self.dict_svg)
        else:
            for ele in svg_list:
                curr_key = ele[path_len + 1: -6];
                if curr_key in self.dict_svg.keys():
                    self.dict_svg[curr_key].append(ele)
                else:
                    self.dict_svg[curr_key] = []
                    self.dict_svg[curr_key].append(ele)
                self.merge_svg(self.dict_svg)
    

    def merge_two(self, svg_node):
        node_key = ""
        flag = False
        for curr_key in svg_node.keys():
            
            node_key = curr_key
            ele_file_list  = svg_node[curr_key]
            merged_svg = ""
            merged_svg = ET.Element('svg')
            root = ET.Element('svg')
            for ele_file in ele_file_list:
                tree = ET.parse(ele_file)
                svg = tree.getroot()
                root.extend(svg)
            merged_svg = ET.tostring(root, encoding='unicode')
            save_svg_path = self.dir_path + "/" + node_key + ".svg"
            with open(save_svg_path , 'w') as file:
                 file.write( merged_svg)
    
            #cairosvg.svg2png(node_key + '.svg', node_key + "_效果图.png")
            cairosvg.svg2png(url = save_svg_path, write_to = self.dir_path +  "/" + node_key + "_效果图.png", dpi=600)


           

    def merge_svg(self, svg_node):        
        node_key = ""
        flag = False
        for curr_key in svg_node.keys(): 
            node_key = curr_key
            ele_file_list  = svg_node[curr_key]
            if len(ele_file_list) == 1:
                continue
            merged_svg = ""
            #merged_svg = ET.Element('svg', width='500', height='500')
            merged_svg = ET.Element('svg')
            #ele_file_list = []
            #ele_file_list .append('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-1.svg')
            #ele_file_list .append('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-2.svg')
            flag = False
            for ele_file in ele_file_list:
                
                ele_root = ET.parse(ele_file).getroot()
                if flag == False:
                    #width = ele_root.get('width')
                    #height = ele_root.get('height')
                    #merged_svg.set("width",width)
                   # merged_svg.set("height",height)
                    flag = True
                    merged_svg.attrib = ele_root.attrib
                for  ele_node in ele_root:
                    merged_svg.append(ele_node)

            save_svg_path = self.dir_path + "/" + node_key + ".svg"

            ET.ElementTree(merged_svg).write( save_svg_path)
            #cairosvg.svg2png(node_key + '.svg', node_key + "_效果图.png")
            write_to_png = write_to = self.dir_path +  "/" + node_key + "_效果图.png"
            #print("save in  ---->" + save_svg_path )
            #print("read from ---->" + save_svg_path + " write to------->" +  write_to_png)

            cairosvg.svg2png(url = save_svg_path, write_to = write_to_png, dpi=600)



class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.setEnabled(True)
        Dialog.resize(959, 539)
        Dialog.setMinimumSize(QtCore.QSize(959, 539))
        Dialog.setMaximumSize(QtCore.QSize(19200, 10800))
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(0, 0, 959, 539))
        self.label.setAcceptDrops(False)
        self.label.setScaledContents(False)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "blob"))
        self.label.setText(_translate("Dialog", "拖拽svg文件或者目录至此处"))

#读取中文路径
def cv_imread(file_path):
    cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
    return cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)

class mwindow(QWidget, Ui_Dialog):
    def __init__(self):
        super(mwindow, self).__init__()
        self.setupUi(self)
        # 调用Drops方法
        self.setAcceptDrops(True)
        # 图片
        self.img = None
    def merg_svg(self,dir_List):
        print("merge")

    # 鼠标拖入事件
    def dragEnterEvent(self, evn):
        # print('鼠标拖入窗口了')
        # 鼠标放开函数事件
        evn.accept()
 
    # 鼠标放开执行
    def dropEvent(self, evn):
        # 判断文件类型
        if evn.mimeData().hasUrls():
            # 获取文件路径
            file_path =  evn.mimeData().urls()[0].toLocalFile()
            url_length = len(evn.mimeData().urls())
            
            if url_length > 1:
                #y拖入的是文件
                svg_list = []

                dir_path = os.path.dirname(evn.mimeData().urls()[0].toLocalFile())
                path_len = len(dir_path)
                for idx in range(0, url_length):
                    curr_file = evn.mimeData().urls()[idx].toLocalFile()
                    file_type = curr_file[-3:]
                    if file_type == "svg":
                        svg_list.append(curr_file)
                if len(svg_list) > 0 :
                    run_svg = MergeSvg()
                    run_svg.dir_path = dir_path
                    run_svg.split_svg(svg_list, path_len, 0)
            else:
                is_dot = file_path[-4: -3]
                if is_dot == ".":
                    return 

                path_len = len(file_path)
                file = file_path
                for root, dirs, files in os.walk(file):
                        if root != file:
                            break
                svg_list = []
                for file in files:
                     path = os.path.join(root, file)
                     file_type = path[-3:]
                     if file_type == "svg":
                         svg_list.append(path)
                     print(path)
                run_svg = MergeSvg()
                dir_path = evn.mimeData().urls()[0].toLocalFile()
                run_svg.dir_path = dir_path
                run_svg.split_svg(svg_list, path_len, 1)

            # opencv 转qimage
            #qimg = QImage(self.img.data, self.img.shape[1], self.img.shape[0], self.img.shape[1]*self.img.shape[2],QImage.Format_RGB888)
            # 显示图片 自适应
            #self.label.setPixmap(QPixmap.fromImage(qimg).scaled(self.label.width(), self.label.height(), Qt.KeepAspectRatio))
        # print('鼠标放开了')
 
    def dragMoveEvent(self, evn):
        pass
        # print('鼠标移入')

if __name__ == '__main__':
    app=QApplication(sys.argv)
    #初始化窗口
    m=mwindow()
    m.show()
    sys.exit(app.exec_())






















# -*- coding: utf-8 -*-

import sys
import time
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
#import cv2
import os
from PyQt5 import QtCore, QtGui, QtWidgets

import xml.etree.ElementTree as ET


import svgutils.transform as sg
from svgutils.compose import Figure


import cairosvg


#svg_path1 = 'C:/Users/16006/Desktop/解析软件的开发/svg文件处理前/30-40-test.svg'
#svg_path2 = 'C:/Users/16006/Desktop/解析软件的开发/svg文件处理前/40-40-东宝5211314-2.svg'
#png_path1 = '1.png'
#png_path2 = '2.png'

#ele_root = ET.parse(svg_path1).getroot()

#width = ele_root.get('width')
#height = ele_root.get('height')
#cairosvg.svg2png(url=svg_path1, write_to=png_path1,dpi=600)
#cairosvg.svg2png(url=svg_path2, write_to=png_path2,dpi=600)
print(121)


#merged_svg = ET.Element('svg')


#svg1 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\60-35-大哪吒和金刚葫芦娃+卡▲-1.svg').getroot()
#svg2 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\60-35-大哪吒和金刚葫芦娃+卡▲-2.svg').getroot()


## Create a new SVG element


## Add the attributes from one of the original SVGs to the merged SVG
#merged_svg.attrib = svg2.attrib

## Add the contents of each SVG to the merged SVG
#for elem in svg1:
#    merged_svg.append(elem)
#for elem in svg2:
#    merged_svg.append(elem)


## Write the merged SVG to a file
#ET.ElementTree(merged_svg).write('merged.svg')



#merged_svg2 = ET.Element('svg')


#svg3 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-1.svg').getroot()
#svg4 = ET.parse('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-2.svg').getroot()


## Create a new SVG element


## Add the attributes from one of the original SVGs to the merged SVG
#merged_svg2.attrib = svg3.attrib

## Add the contents of each SVG to the merged SVG
#for elem in svg3:
#    merged_svg.append(elem)
#for elem in svg4:
#    merged_svg.append(elem)


## Write the merged SVG to a file
#ET.ElementTree(merged_svg).write('merged2.svg')










class MergeSvg(object):
    dict_svg = {}
    dir_path = './'
    def split_svg(self, svg_list, path_len, isdir):
        if isdir == 1:
            for ele in svg_list:
                curr_key =  ele[path_len + 1: -6]
                if curr_key in self.dict_svg.keys():
                    self.dict_svg[curr_key].append(ele)
                else:
                    self.dict_svg[curr_key] = []
                    self.dict_svg[curr_key].append(ele)
            #self.merge_svg(self.dict_svg)
            self.merge_svg(self.dict_svg)
        else:
            for ele in svg_list:
                curr_key = ele[path_len + 1: -6];
                if curr_key in self.dict_svg.keys():
                    self.dict_svg[curr_key].append(ele)
                else:
                    self.dict_svg[curr_key] = []
                    self.dict_svg[curr_key].append(ele)
                self.merge_svg(self.dict_svg)
    

    def merge_two(self, svg_node):
        node_key = ""
        flag = False
        for curr_key in svg_node.keys():
            
            node_key = curr_key
            ele_file_list  = svg_node[curr_key]
            merged_svg = ""
            merged_svg = ET.Element('svg')
            root = ET.Element('svg')
            for ele_file in ele_file_list:
                tree = ET.parse(ele_file)
                svg = tree.getroot()
                root.extend(svg)
            merged_svg = ET.tostring(root, encoding='unicode')
            save_svg_path = self.dir_path + "/" + node_key + ".svg"
            with open(save_svg_path , 'w') as file:
                 file.write( merged_svg)
    
            #cairosvg.svg2png(node_key + '.svg', node_key + "_效果图.png")
            cairosvg.svg2png(url = save_svg_path, write_to = self.dir_path +  "/" + node_key + "_效果图.png", dpi=600)


           

    def merge_svg(self, svg_node):        
        node_key = ""
        flag = False
        for curr_key in svg_node.keys(): 
            node_key = curr_key
            ele_file_list  = svg_node[curr_key]
            if len(ele_file_list) == 1:
                continue
            merged_svg = ""
            #merged_svg = ET.Element('svg', width='500', height='500')
            merged_svg = ET.Element('svg')
            #ele_file_list = []
            #ele_file_list .append('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-1.svg')
            #ele_file_list .append('C:/Users/16006/Desktop/解析软件的开发/svg文件处理前\\40-40-东宝5211314-2.svg')
            flag = False
            for ele_file in ele_file_list:
                
                ele_root = ET.parse(ele_file).getroot()
                if flag == False:
                    #width = ele_root.get('width')
                    #height = ele_root.get('height')
                    #merged_svg.set("width",width)
                   # merged_svg.set("height",height)xmlns="http://www.w3.org/2000/svg"
                    
                    flag = True
                    merged_svg.attrib = ele_root.attrib
                    merged_svg.set("xmlns", "http://www.w3.org/2000/svg")
                for  ele_node in ele_root:
                    merged_svg.append(ele_node)

            save_svg_path = self.dir_path + "/" + node_key + ".svg"

            ET.ElementTree(merged_svg).write( save_svg_path)
            #cairosvg.svg2png(node_key + '.svg', node_key + "_效果图.png")
            write_to_png = write_to = self.dir_path +  "/" + node_key + "_效果图.png"
            #print("save in  ---->" + save_svg_path )
            #print("read from ---->" + save_svg_path + " write to------->" +  write_to_png)

            cairosvg.svg2png(url = save_svg_path, write_to = write_to_png, dpi=50)



class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.setEnabled(True)
        Dialog.resize(959, 539)
        Dialog.setMinimumSize(QtCore.QSize(959, 539))
        Dialog.setMaximumSize(QtCore.QSize(19200, 10800))
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(0, 0, 959, 539))
        self.label.setAcceptDrops(False)
        self.label.setScaledContents(False)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "blob"))
        self.label.setText(_translate("Dialog", "拖拽svg文件或者目录至此处"))

#读取中文路径
def cv_imread(file_path):
    cv_img = cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
    return cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB)

class mwindow(QWidget, Ui_Dialog):
    def __init__(self):
        super(mwindow, self).__init__()
        self.setupUi(self)
        # 调用Drops方法
        self.setAcceptDrops(True)
        # 图片
        self.img = None
    def merg_svg(self,dir_List):
        print("merge")

    # 鼠标拖入事件
    def dragEnterEvent(self, evn):
        # print('鼠标拖入窗口了')
        # 鼠标放开函数事件
        evn.accept()
 
    # 鼠标放开执行
    def dropEvent(self, evn):
        # 判断文件类型
        if evn.mimeData().hasUrls():
            # 获取文件路径
            file_path =  evn.mimeData().urls()[0].toLocalFile()
            url_length = len(evn.mimeData().urls())
            
            if url_length > 1:
                #y拖入的是文件
                svg_list = []

                dir_path = os.path.dirname(evn.mimeData().urls()[0].toLocalFile())
                path_len = len(dir_path)
                for idx in range(0, url_length):
                    curr_file = evn.mimeData().urls()[idx].toLocalFile()
                    file_type = curr_file[-3:]
                    if file_type == "svg":
                        svg_list.append(curr_file)
                if len(svg_list) > 0 :
                    run_svg = MergeSvg()
                    run_svg.dir_path = dir_path
                    run_svg.split_svg(svg_list, path_len, 0)
            else:
                is_dot = file_path[-4: -3]
                if is_dot == ".":
                    file_type = file_path[-3:]
                    if  file_type == "svg":
                        print("svg")
                        run_svg = MergeSvg()
                        run_svg.dir_path = os.path.dirname(evn.mimeData().urls()[0].toLocalFile())
                        single_file = evn.mimeData().urls()[0].toLocalFile()
                        path_len = len(run_svg.dir_path)
                        node_key = single_file[path_len + 1: -6]
                        #svg_list = []
                        #svg_list.append(evn.mimeData().urls()[0].toLocalFile())
                        #run_svg.split_svg(svg_list, path_len, 0)

                        cairosvg.svg2png(url = single_file, write_to = run_svg.dir_path +  "/" + node_key + "_效果图.png", dpi=50)
                        return 
                    else:
                        return 

                path_len = len(file_path)
                file = file_path
                for root, dirs, files in os.walk(file):
                        if root != file:
                            break
                svg_list = []
                for file in files:
                     path = os.path.join(root, file)
                     file_type = path[-3:]
                     if file_type == "svg":
                         svg_list.append(path)
                     print(path)
                run_svg = MergeSvg()
                dir_path = evn.mimeData().urls()[0].toLocalFile()
                run_svg.dir_path = dir_path
                run_svg.split_svg(svg_list, path_len, 1)

            # opencv 转qimage
            #qimg = QImage(self.img.data, self.img.shape[1], self.img.shape[0], self.img.shape[1]*self.img.shape[2],QImage.Format_RGB888)
            # 显示图片 自适应
            #self.label.setPixmap(QPixmap.fromImage(qimg).scaled(self.label.width(), self.label.height(), Qt.KeepAspectRatio))
        # print('鼠标放开了')
 
    def dragMoveEvent(self, evn):
        pass
        # print('鼠标移入')

if __name__ == '__main__':
    app=QApplication(sys.argv)
    #初始化窗口
    m=mwindow()
    m.show()
    sys.exit(app.exec_())




